package com.web.controller;

import com.alibaba.fastjson.JSON;
import com.web.entity.ResponseResult;
import com.web.entity.Student;
import com.web.service.StudentService;
import com.web.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/findStudentById")
public class FindStudentByIdServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");

        // 获取请求参数
        String idStr = req.getParameter("id");
        if (idStr == null || idStr.isEmpty()) {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(400, "ID不能为空", null)));
            return;
        }

        try {
            int id = Integer.parseInt(idStr);
            StudentService studentService = new StudentServiceImpl();
            Student student = studentService.findStudentById(id);

            if (student == null) {
                resp.getWriter().write(JSON.toJSONString(new ResponseResult(404, "未找到学生", null)));
            } else {
                resp.getWriter().write(JSON.toJSONString(new ResponseResult(200, "OK", student)));
            }
        } catch (NumberFormatException e) {
            resp.getWriter().write(JSON.toJSONString(new ResponseResult(400, "ID格式不正确", null)));
        }
    }
}
